/*
     Copyright 2007 Joseph M. Ferner

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.IO;
using System.Text;

namespace OpenServers.Net.Common.Utils {
    /// <summary>
    /// Collection of methods for working with <see cref="Stream"/>s.
    /// </summary>
    public class StreamUtils {
        /// <summary>
        /// Copy one stream to the other.
        /// </summary>
        public static long Copy(Stream input, Stream output) {
            if (input == null || !input.CanRead) {
                throw new ArgumentException("input is null or cannot be read");
            } if (output == null || !output.CanWrite) {
                throw new ArgumentException("output is null or cannot be written to");
            }

            byte[] buffer = new byte[10 * 1024];
            long count = 0;
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0) {
                output.Write(buffer, 0, read);
                count += read;
            }
            return count;
        }

        /// <summary>
        /// Reads the stream into a string using ASCII encoding.
        /// </summary>
        public static string ToString(Stream input) {
            StringBuilder result = new StringBuilder();
            byte[] buffer = new byte[10 * 1024];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0) {
                result.Append(Encoding.ASCII.GetString(buffer, 0, read));
            }
            return result.ToString();
        }
    }
}
